package com.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

@SuppressWarnings(value = { "unchecked" })
public class MenuGenerator
{
	public Document getMenuDocument()  throws Exception
	{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(MenuGenerator.class.getResourceAsStream("leftMenu.xml"));
		return doc;
	}
	
	public List getMenuList() throws Exception
	{
		List menus = new ArrayList();
		Document menuDoc = getMenuDocument();
		Element root = menuDoc.getRootElement();
		for(Iterator iter = root.elementIterator("menuItem"); iter.hasNext();)
		{
			Element elmt = (Element)iter.next();
			String index = elmt.attributeValue("index");
			String name = elmt.attributeValue("name");
			
			MenuItem menuItem = new MenuItem();
			menuItem.setIndex(index);
			menuItem.setName(name);
			
			String defaultImg = elmt.attributeValue("defaultImg");
			String defaultHref = elmt.attributeValue("defaultHref");
			String defaultTarget = elmt.attributeValue("defaultTarget");
			
			List childElements = menuDoc.selectNodes("//menuConfig/menuItem[@index='"+index+"']/childMenuItem");
			List childMenuItems = new ArrayList();
			for(Iterator iter2 = childElements.iterator(); iter2.hasNext();)
			{
				Element elmt2 = (Element) iter2.next();
				String index2 = elmt2.attributeValue("index");
				String name2 = elmt2.attributeValue("name");
				String img = elmt2.attributeValue("img");
				String href = elmt2.attributeValue("href");
				String target = elmt2.attributeValue("target");
				if(img == null) img = defaultImg;
				if(href == null) href = defaultHref;
				if(target == null) target = defaultTarget;
				
				Node prop = menuDoc.selectSingleNode("//menuConfig/menuItem[@index='"+index+"']/childMenuItem[@index='"+index2+"']/prop");
				Map map = new HashMap();
				map.put(prop.getName(),prop.getText());

				ChildMenuItem cmi = new ChildMenuItem();
				cmi.setIndex(index2);
				cmi.setName(name2);
				cmi.setImg(img);
				cmi.setHref(href);
				cmi.setTarget(target);
				cmi.setProps(map);
				childMenuItems.add(cmi);
			}
			
			menuItem.setChildMenuItems(childMenuItems);
			menus.add(menuItem);
		}
		
		return menus;
		
	}
	
	public static void main(String[] args) throws Exception
	{
		MenuGenerator mg = new MenuGenerator();
		//Document doc = mg.getMenuDocument();
		List childElements = mg.getMenuList();
		MenuItem mi = (MenuItem) childElements.get(1);
		List list = mi.getChildMenuItems();
		for(int i = 0;i < list.size();i++)
		{
			ChildMenuItem c = (ChildMenuItem) list.get(i);
			System.out.println(c.getIndex()+":"+c.getName());
		}
	}
}
